﻿using Microsoft.Win32;
using System;
using System.Windows;
using HalconDotNet;
using Euresys;

namespace EGrabberWpf4Gain
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Euresys.EGenTL genTL;      
        private Euresys.EGrabberCallbackSingleThread myEGrabber;
        private volatile bool grabbing;
        private volatile bool stopping;    
        UInt64 width;
        UInt64 height;
        String format;
   

        string pathImage = "d:\\EGrabber4Image";

        public MainWindow()
        {
            InitializeComponent();
            this.ContentRendered += MainWindow_ContentRendered;
        }

        private void MainWindow_ContentRendered(object sender, EventArgs e)
        {
           
            //判断js文件是否存在
            string jsPath = string.Format("{0}config.js", AppDomain.CurrentDomain.BaseDirectory);
            if(System.IO.File.Exists(jsPath))
                txtJsPath.Text = jsPath;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == true)                     
                txtJsPath.Text = openFileDialog.FileName;
        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                if(genTL==null)
                genTL = new Euresys.EGenTL();       
                myEGrabber = new Euresys.EGrabberCallbackSingleThread(genTL);
                if (System.IO.File.Exists(txtJsPath.Text))
                {
                    myEGrabber.runScript(txtJsPath.Text);
                }
                myEGrabber.reallocBuffers(1);

                width = myEGrabber.getWidth();
                height = myEGrabber.getHeight();
                format = myEGrabber.getPixelFormat();


                lb.Items.Add(string.Format("width : {0}  height {1} format : {2}",width, height, format));


                startStream();
                btnOpen.IsEnabled = false;
            }
            catch(Exception ex)
            {
                lb.Items.Add(string.Format("{0} error {1}", DateTime.Now.ToString("HH:mm:ss fff"), ex.Message));

                if (genTL != null)
                {
                    genTL.Dispose();
                    genTL = null;
                }
                if (myEGrabber != null)
                {
                    myEGrabber.Dispose();
                    myEGrabber = null;
                }
            }
           if(isSaveImage)
            {
                System.IO.Directory.CreateDirectory(pathImage);
            }
            num = 0;

        }

        private void btnClos_Click(object sender, RoutedEventArgs e)
        {
            stopStream();        

            if (hoTemp!=null)
            {
                hoTemp.Dispose();
                hoTemp = null;
            }
            btnOpen.IsEnabled = true;
        }

        private void btnGain_Click(object sender, RoutedEventArgs e)
        {
            float _gain = 0;
            try
            {
                _gain =(float) Convert.ToDouble(txtGain.Text.Trim());

            }
            catch(Exception ex)
            {
                MessageBox.Show(string.Format("Gain 数值不正确！{0}",ex.Message));
            }
            if (myEGrabber != null)
            {
                try
                {
                    // 设置相机的增益值
                    myEGrabber.setFloatRemoteModule("DigitalGain", _gain); // 设置增益值为10，具体值根据实际情况调整
                    lb.Items.Add(string.Format("{0} DigitalGain {1}", DateTime.Now.ToString("HH:mm:ss fff"), _gain));
                }
                catch(Exception ex)
                {
                    lb.Items.Add(string.Format("{0} DigitalGain {1} error {2}", DateTime.Now.ToString("HH:mm:ss fff"), _gain,ex.Message));
                }

              

            }
        }



        public void startStream()
        {
            if (!grabbing && myEGrabber != null)
            {
                stopping = false;
                myEGrabber.onNewBufferEvent = onNewBuffer;
                myEGrabber.start();
                grabbing = true;
            }
        }

        public void stopStream()
        {
            if (grabbing && myEGrabber != null)
            {
                stopping = true;
                myEGrabber.stop();
                myEGrabber.flushAllEvent();
                myEGrabber.onNewBufferEvent = null;
                grabbing = false;

                myEGrabber.Dispose();
                myEGrabber = null;
            }
        }


        public void onNewBuffer(Euresys.EGrabberCallbackSingleThread g, Euresys.NewBufferData data)
        {
            if (stopping )
            {
                // when stopping: the grabber is busy stopping or flushing events
                // when disposed: the grabber and converter objects have been destroyed
                return;
            }
            using (Euresys.ScopedBuffer buffer = new Euresys.ScopedBuffer(g, data))
            {
                IntPtr bufferPtr;
                buffer.getInfo(Euresys.gc.BUFFER_INFO_CMD.BUFFER_INFO_BASE, out bufferPtr);                

                num++;          

                HOperatorSet.GenImage1(out hoTemp, "byte", width, height, bufferPtr);

                if (isSaveImage)
                {
                    HOperatorSet.WriteImage(hoTemp, "tiff", 0, string.Format("{0}\\{1}.tif", pathImage, num%10));
                }
                if(hoTemp!=null)
                {
                    hoTemp.Dispose();
                }

                Dispatcher.Invoke(new System.Action(() =>
                {

                    lb.Items.Add(string.Format("{0} image {1}", DateTime.Now.ToString("HH:mm:ss fff"), num));

                }));
            }
        }

        HObject hoTemp;
        bool isSaveImage=true;
        int num;

        private void chkSaveImage_Click(object sender, RoutedEventArgs e)
        {
            isSaveImage = chkSaveImage.IsChecked.GetValueOrDefault();
        }
    }
}
